package com.jg.visitor.filter;

import com.jg.visitor.GlobalConst;
import com.jg.visitor.common.bean.ResponseBean;
import com.jg.visitor.common.bean.ServiceCode;
import com.jg.visitor.common.utils.*;
import com.jg.visitor.controller.dto.UserDTO;
import com.jg.visitor.service.UserService;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebFilter(filterName="OpenIdFilter",urlPatterns="/*")
@Order(1)
@Slf4j
public class OpenIdFilter implements Filter {

    @Resource
    private UserService userService;

    @Override
    public void init(FilterConfig filterConfig) {
        log.info("openIdFilter init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String path = ((HttpServletRequest) servletRequest).getServletPath();


        if(!CheckParamUtils.checkUrlBaseAllowed(path)){

            //缓存获取当前登录用户
            UserDTO userDTO = LoginHelper.getLoginVisitor();

            try{
                //如果缓存用户没有，则通过token中携带的openId重新设置登录访客
                if(null == userDTO){

                    try{
                        //检测token并获取openId
                        String openIdByToken = LoginHelper.checkVisitorOpenIdSign();

                        if(!StringUtils.isEmpty(openIdByToken)){
                            userDTO = userService.getUserDTObyOpenId(openIdByToken);
                            if(null != userDTO){
                                userDTO.setToken(LoginHelper.getRequestToken(GlobalConst.VISITOR_TOKEN));
                                LoginHelper.setLoginVisitor(userDTO);
                            }
                        }
                    }catch (ExpiredJwtException e){
                        ResponseUtil.out((HttpServletResponse)servletResponse, ResponseBean.error(ServiceCode.UNAUTHORIZED));
                        return;
                    }
                }
            }catch (Exception e){
                log.error("get login visitor by token error",e);
            }

            //如果token里面也没有openId,则代表没有初始化，没有权限
            if(null == userDTO){
                ResponseUtil.out((HttpServletResponse)servletResponse, ResponseBean.error(ServiceCode.UNAUTHORIZED));
                return;
            }
        }

        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        log.info("openIdFilter destroy");
    }

}
